package cn.edu.cqytxy.servlet;

import cn.edu.cqytxy.entity.Weapon;
import cn.edu.cqytxy.service.WeaponService;
import cn.edu.cqytxy.util.DBUtils;
import com.alibaba.fastjson2.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用来接受和处理Weapon相关的请求
 *
 * @author yinjw
 */
public class WeaponServlet extends HttpServlet {

    WeaponService weaponService = new WeaponService();

    @Override
    public void init() throws ServletException {

        System.out.println("init方法被执行");

        // 初始化数据库连接
        DBUtils.getConn();
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("doGet被访问");
        req.setCharacterEncoding("utf-8");

        // 通过HttpServletRequest.getParameter() 获取传参
        // getParameter方法只能把参数转化为字符串解析
        String name = req.getParameter("name");
        Weapon[] weapons = weaponService.getWeapons(name);

        String resStr = JSON.toJSONString(weapons);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(resStr);
    }

    @Override
    public void destroy() {
        System.out.println("destroy方法被执行");
        DBUtils.closeConn();
    }
}
